﻿using Furion.DependencyInjection;
using Furion.Logging;
using Furion.RemoteRequest.Extensions;
using Microsoft.Extensions.Caching.Memory;
using FaceMqttClient.model;
using MqttModel;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FaceMqttClient
{
    public class WeixinTongzhi : ITransient
    {
        private  ISugarQueryable<kq_setting> sqlSugarRepository;
        private readonly ISugarQueryable<Lesson> lesson;
        private readonly IMemoryCache memoryCache;
        private readonly ISqlSugarClient db;
        public WeixinTongzhi(ISqlSugarClient db, IMemoryCache memoryCache)
        {
            this.sqlSugarRepository = db.Queryable<kq_setting>();
            this.lesson = db.Queryable<Lesson>();
            this.memoryCache = memoryCache;
            this.db = db;
        }

        /// <summary>
        /// 获取考勤记录
        /// </summary>
        public DataTable getUnsend()
        {

            //会员到期时间
            String daoqtime = DateTime.Now.Date.ToString("yyyy/MM/dd");
            // 通知有效时间
            String TongzhiTime = DateTime.Now.AddHours(-1).ToString("yyyy/MM/dd HH:mm:ss");

            string sql = $"SELECT `lxb_user`.`slname`, `lxb_user`.`zschool`, `lxb_user`.`dx`,`lxb_user`.`clname`,`lxb_user`.`username`,`lxb_user`.`classname`, `lxb_device`.`address`,`lxb_kaoqin_log`.`sn`, `lxb_device`.`Notify`, `lxb_kaoqin_log`.`Id` as uid, `lxb_kaoqin_log`.`time`, `lxb_kaoqin_log`.`state`, `lxb_kaoqin_log`.`Lid`, `lxb_device`.`FangXiang` as `io`, `lxb_kaoqin_log`.`tiwen`, `lxb_kaoqin_log`.`adid` FROM `lxb_kaoqin_log` INNER JOIN `lxb_device` ON `lxb_kaoqin_log`.`sn`=`lxb_device`.`SN` JOIN `lxb_user` ON `lxb_user`.`user_id`=`lxb_kaoqin_log`.`id` and `lxb_user`.`state` IN(3,4) WHERE `lxb_user`.`kqtime` > '{daoqtime}' AND `lxb_kaoqin_log`.`time` >= '{TongzhiTime}' AND `wxtz` = 0 ORDER  BY lid LIMIT 200  ";
            // Console.WriteLine(sql);
            var dtable = db.Ado.GetDataTable(sql);
            return dtable;
        }


        /// <summary>
        /// 获取到期记录
        /// </summary>
        public DataTable getEndsend()
        {

            //会员到期时间
            String daoqtime2 = DateTime.Now.AddDays(+1).Date.ToString("yyyy/MM/dd");
            String daoqtime1 = DateTime.Now.Date.ToString("yyyy/MM/dd");


            string sql = $"SELECT `lxb_user`.`slname`, `lxb_user`.`zschool`, `lxb_user`.`dx`,`lxb_user`.`clname`,`lxb_user`.`username`,`lxb_user`.`classname`,`lxb_user`.`user_id`  FROM  `lxb_user`  INNER JOIN  lxb_adschool ON lxb_adschool.name =lxb_user.slname AND lxb_adschool.cuifei =1  WHERE (`lxb_user`.`kqtime` = '{daoqtime2}'  or `lxb_user`.`kqtime` = '{daoqtime1}'  ) AND  `lxb_user`.`state` IN(3) ORDER  BY user_id";
             Console.WriteLine(sql);
            var dtable = db.Ado.GetDataTable(sql);
            return dtable;
        }


        /// <summary>
        /// 获取需要通知的老师
        /// </summary>
        /// <param name="uid"></param>
        public DataTable getTongzhiTeacher(string classid)
        {
            var tl = lesson.Where(l => l.lessclass == classid && l.lessuser != "").Select(l => l.lessuser).ToArray();
            if (tl.Count() == 0)
            {
                return null;

            }
            var keys = String.Join(",", tl);

            string teacher = $"{keys}";
            String daoqtime = DateTime.Now.Date.ToString("yyyy/MM/dd");
            var sql = "SELECT `lxb_user`.`username` ,  `slname`, `oauth_id`, `lxb_user`.`user_id`, `lxb_member_oauth`.`nickname` " +
                "FROM `lxb_huiyuan` JOIN `lxb_user` ON `lxb_huiyuan`.`teacher`=`lxb_user`.`user_id` " +
                "JOIN `lxb_member_oauth` ON `lxb_huiyuan`.`ID`=`lxb_member_oauth`.`UID`" +
                $" WHERE `teacher` in ({teacher}) AND  `oauth_type` = 'wechat' ";
            var dtable = db.Ado.GetDataTable(sql);
            return dtable;
        }

        /// <summary>
        /// 获取需要通知的人
        /// </summary>
        /// <param name="uid"></param>
        public DataTable getTongzhi(string uid)
        {
            String daoqtime = DateTime.Now.Date.ToString("yyyy/MM/dd");
            var sql = $"SELECT `lxb_user`.`username`, `slname`, `oauth_id`, `lxb_user`.`user_id`, `lxb_member_oauth`.`nickname` FROM `lxb_rel_huiyuan` JOIN `lxb_user` ON `lxb_rel_huiyuan`.`RUID`=`lxb_user`.`user_id` JOIN `lxb_member_oauth` ON `lxb_rel_huiyuan`.`UID`=`lxb_member_oauth`.`UID` WHERE `RUID` = '{uid}' AND `lxb_user`.`tz` = 1 AND `oauth_type` = 'wechat' AND `lxb_user`.`kqtime` > '{daoqtime}'";
            var dtable = db.Ado.GetDataTable(sql);
            return dtable;
        }


        /// <summary>
        /// 获取到期需要通知的人
        /// </summary>
        /// <param name="uid"></param>
        public DataTable getDaoqiTongzhi(string uid)
        {
        
            var sql = $"SELECT `lxb_user`.`username`, `slname`, `oauth_id`, `lxb_user`.`user_id`, `lxb_member_oauth`.`nickname` FROM `lxb_rel_huiyuan` JOIN `lxb_user` ON `lxb_rel_huiyuan`.`RUID`=`lxb_user`.`user_id` JOIN `lxb_member_oauth` ON `lxb_rel_huiyuan`.`UID`=`lxb_member_oauth`.`UID` WHERE `RUID` = '{uid}' AND `lxb_user`.`tz` = 1 AND `oauth_type` = 'wechat'";
            var dtable = db.Ado.GetDataTable(sql);
            return dtable;
        }

        public void Sended(int Lid)
        {
            var sql = $"update lxb_kaoqin_log set wxtz=1 where Lid={Lid}";
            var dtable = db.Ado.ExecuteCommand(sql);
        }

        public async  Task<bool> cansend(String schoolname, DataRow r)
        {
            try
            {
                var kqs =  await getkxs(schoolname.Trim());

                if (kqs != null)
                {
                    Console.WriteLine($"{schoolname}考勤已经设置");
                    var time = Convert.ToDateTime(r["time"]);
                    foreach (var kq in kqs)
                    {


                        // print_r($kqs);
                        var date = time.Date.ToString("yyyy/MM/dd");
                        var sts = Convert.ToDateTime($"{date} {kq.StartS}");
                        var ste = Convert.ToDateTime($"{date} {kq.StartE}");
                        var ends = Convert.ToDateTime($"{date} {kq.EndS}");
                        var ende = Convert.ToDateTime($"{date} {kq.EndE}");

                    //    Console.WriteLine($" {sts.ToString("F")},{ste.ToString("F")},{ends.ToString("F")},{ende.ToString("F")}");

                    //    StringLoggingPart.Default().SetMessage($" {sts.ToString("F")},{ste.ToString("F")},{ends.ToString("F")},{ende.ToString("F")}").LogWarning();
                        if (((time <= ste) && (time >= sts)) ||
                                ((time <= ende) && (time >= ends)))
                        {
                           // Console.WriteLine(schoolname + "有效时间");
                            StringLoggingPart.Default().SetMessage($"  {schoolname}" + r["username"] + " 时间 " + r["time"] + "  发送").LogWarning();

                            return true;
                        }
                      
                    }
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(" 没有有效时间 " + r["time"]);
                    Console.WriteLine(schoolname + "无效时间 不发送");
                    StringLoggingPart.Default().SetMessage($" {schoolname}" + r["username"] + " 时间 " + r["time"] + "  不发送").LogWarning();
                    Console.ForegroundColor = ConsoleColor.White;

                }
                else
                {
                    Console.WriteLine("{schoolname}考勤未设置 不发送");
                    StringLoggingPart.Default().SetMessage($"{schoolname}考勤未设置 不发送").LogWarning();

                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("是否可以发送报错" + ex.Message);

            }
            return false;

        }



        public async Task<bool> Isholiday(DateTime dt)
        {
            var key = dt.ToString("yyyy-MM-dd");
            var rlt = memoryCache.Get("holiday_" + key);
            if (rlt == null)
            {
                HolidayModel hm = await ("http://timor.tech/api/holiday/info/" + key).GetAsAsync<HolidayModel>();

                var st = (hm.type.type == TypeEnum.周末 || hm.type.type == TypeEnum.节日);

                memoryCache.Set("holiday_" + key, st, DateTime.Now.AddDays(1));

                return st;
            }
            return (Boolean)rlt;

        }

        internal Boolean LeaveSchool(string schoolname)
        {
            var schl = getSchool(schoolname);
            if (schl != null && schl.leavets == 1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public School getSchool(string school)
        {
            var rlt = memoryCache.Get(school);
            if (rlt == null)
            {
                var aschool = db.Queryable<School>().Where(sc => sc.name == school).First();

                memoryCache.Set(school, aschool, DateTime.Now.AddMinutes(1));
                return aschool;
            }
            return rlt as School;


        }
        public async Task<List<kq_setting>> getkxs(String school)
        {

            var rlt = memoryCache.Get("kqs_" + school);
            if (rlt == null)
            {
                sqlSugarRepository = db.Queryable<kq_setting>();
                
                var st = await sqlSugarRepository.Where(sql => sql.Type.Equals("学生") && sql.School.Equals(school)).ToListAsync();
               // Console.WriteLine(sqlSugarRepository.ToSqlString());
                if (st.Count == 0)
                {
                    return null;
                }
                memoryCache.Set("kqs_" + school, st, DateTime.Now.AddMinutes(10));
                
                return (st);
            }


            return (List<kq_setting>)rlt;

        }
    }
}
